package com.example.stretching;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;

import android.R.integer;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.example.db.DLog;
import com.example.db.Databases;
import com.example.db.Databases.CreateDB;
import com.example.db.DbopenHelper;
import com.google.android.gms.internal.md;

/**
 * 
 *리스트 눌렀을 때 시간, 요일 수정
 *RealMainActivit
 *버튼 클릭하면 dialog로 시작, 끝 시간, 요일 변경
 *dialog 내에서도 timepicker dialog가 뜨는 등 override 가 너무 많이 되서
 *case 문으로 버튼의 R.id값을 받아서 custom dialog를 띄우게 함 
 *@author DS
 */
public class modifyScheduleActivity extends Activity implements OnItemClickListener, OnClickListener{
	
	private DbopenHelper mDbOpenHelper;
	public static final int DEFAULT_ALARM_REQUEST = 800;

	static int reqCode = DEFAULT_ALARM_REQUEST
			+ MainActivity.arrayListAlarmTimeItem.size();	
	static AlarmManager alarmManager;

	private TextView time,time2, day;
	Context context;
	private CustomDialog mCustomDialog;

	private final Calendar datetime = Calendar.getInstance();
	private final Calendar datetime2 = Calendar.getInstance();
	
	private Switch mSwitch;
	

//
//	static int q;
//	static ArrayList<Integer> oPerlishArray = new ArrayList<Integer>();
//	static int q_size = oPerlishArray.size();
	public GregorianCalendar gregorianCalendar = new GregorianCalendar(
			TimeZone.getTimeZone("GMT+09:00"));
	static boolean noti;


	ArrayList<String> notnullweek = new ArrayList<String>();
	static ArrayList<String> dayofweek_ = new ArrayList<String>();

	static CheckBox mon_check, tue_check, wed_check, thu_check, fri_check, sat_check, sun_check;
	private Dialog mMainDialog;
	private Context mContext;

//	String completed_;

//	static int q;
//	static ArrayList<Integer> oPerlishArray = new ArrayList<Integer>();
//	static int q_size = oPerlishArray.size();
	
	 private ArrayList<Custom_List_Data> Array_Data;
	    public Custom_List_Data data;
	    public Custom_List_Adapter adapter3;
    ListView custom_list;
   
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_content);
		mContext = getApplicationContext();
	
		mSwitch = (Switch)findViewById(R.id.on_off_View);
		 loadSavedPreferences();
		
		SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
        pref.getBoolean("checked", false);
	
		
//		GcmMainActivity.service = false;
		// j = hour3- hour1, jj = hour1, jjj = hour3 jjjj = hour2, jjjjj = hour4
		Intent intent = getIntent();
		
//		if(intent.getStringExtra("onoff")== "ON"){
//     		mSwitch.setChecked(true);}
// 		else if(intent.getStringExtra("onoff") == "OFF"){
// 			mSwitch.setChecked(false);
// 		}
//		Log.d("onoff_modi",intent.getStringExtra("onoff"));
		int jjjjj = intent.getIntExtra("data_hour4", 0);
		int jjj = intent.getIntExtra("data_hour3", 0);
		int jj = intent.getIntExtra("data_hour1", 0);
		
	
		
		if((intent.getIntExtra("data_hour3", 0) <= intent.getIntExtra("data_hour1", 0))){
			jjj = jjj + 24;
			
		}
		int j = jjj - jj;
		
		int jjjj = intent.getIntExtra("data_hour2", 0);
		Random rand = new Random(System.currentTimeMillis());  
		int r = rand.nextInt(5)+1;
		   //씨드값을 배정하여 생성  
//		if(AnimationPage.complete = true){

//		}
//		else if (AnimationPage.complete = false){
//			String a = "";
//		};
		  Array_Data = new ArrayList<Custom_List_Data>();
		  Log.d("J", Integer.toString(j));
		  
		  Intent intent9 = getIntent();
		  String a = "Completed!";
		  String b = "";
		  
		  long today = System.currentTimeMillis(); // long 형의 현재시간
	
		  Calendar hour_jj = Calendar.getInstance();
		
		  Log.d("hour_jj", Integer.toString(hour_jj.get(Calendar.HOUR_OF_DAY)));
//		  System.out.println(str);
		  // && hour_jj.get(Calendar.HOUR_OF_DAY) == jj + q
			int q=1;
//			 if(tabMainActivity.complete == true && tabMainActivity.time_tab < AlarmReceive.time_alarm + 100000){
		  for(q=1; q<j; q++){
			 
			  if(q % 5  == 0  && AlarmAdapter.complete == "Completed!"){
						
	        data = new Custom_List_Data(R.drawable.icon_1,jj +q+":" +jjjj + "   Do Stretching!!!", a); 
	        Array_Data.add(data);}
			  else if(q % 5 ==0){
				  data = new Custom_List_Data(R.drawable.icon_1,jj +q+":" +jjjj + "   Do Stretching!!!", b); 
			        Array_Data.add(data);
			  };
			  if(q % 5 == 1 && hour_jj.get(Calendar.HOUR_OF_DAY) == jj + q){
		    data = new Custom_List_Data(R.drawable.icon_2, jj +q+":" +jjjj + "   Stand-up!!!", a);
	        Array_Data.add(data);}
			  else if(q % 5 == 2 && hour_jj.get(Calendar.HOUR_OF_DAY) == jj + q){
			
			data = new Custom_List_Data(R.drawable.icon_3, jj +q+":" +jjjj + "   Do Exercise!!!", a);
			Array_Data.add(data);}
			  else if(q % 5 == 3 && hour_jj.get(Calendar.HOUR_OF_DAY) == jj + q){
				
			data = new Custom_List_Data(R.drawable.icon_4, jj +q+":" +jjjj + "   Stand-up!!!", a);
			Array_Data.add(data);}
			  else if(q % 5 == 4 && hour_jj.get(Calendar.HOUR_OF_DAY) == jj + q){
		
			data = new Custom_List_Data(R.drawable.icon_5, jj +q+":" +jjjj + "   Do Stretching!!!", a);
			Array_Data.add(data);}
		  };
//			}

//			else if(tabMainActivity.complete == false || hour_jj.get(Calendar.HOUR) == 0){
				  for(q=1; q<j; q++){
					  if(q % 5  == 0 ){
								
			        data = new Custom_List_Data(R.drawable.icon_1,jj +q+":" +jjjj + "   Do Stretching!!!", b); 
			        Array_Data.add(data);}
					  else if(q % 5 == 1){
				    data = new Custom_List_Data(R.drawable.icon_2, jj +q+":" +jjjj + "   Stand-up!!!", b);
			        Array_Data.add(data);}
					  else if(q % 5 == 2){
					
					data = new Custom_List_Data(R.drawable.icon_3, jj +q+":" +jjjj + "   Do Exercise!!!", b);
					Array_Data.add(data);}
					  else if(q % 5 == 3){
						
					data = new Custom_List_Data(R.drawable.icon_4, jj +q+":" +jjjj + "   Stand-up!!!", b);
					Array_Data.add(data);}
					  else if(q % 5 == 4){
				
					data = new Custom_List_Data(R.drawable.icon_5, jj +q+":" +jjjj + "   Do Stretching!!!", b);
					Array_Data.add(data);}
				  };
//			}
	        ListView custom_list = (ListView) findViewById(R.id.notilistView_Set);
	        Custom_List_Adapter.custom_ = new Custom_List_Adapter(this,
	                android.R.layout.simple_list_item_1, Array_Data);
	 	      Log.d("data", Array_Data.toString());
	        custom_list.setAdapter(Custom_List_Adapter.custom_);
        day = (TextView)findViewById(R.id.Day_content); //id값이 제대로 전달 되었는지 찍어주는 곳
//		final int id = Integer.parseInt(intent.getStringExtra("data_id"));
       
//        intent.getStringExtra("data_id");
     
        
        time = (TextView)findViewById(R.id.Time_content_FROM);
        time.setText(Integer.toString(intent.getIntExtra("data_hour1", 0))+
        	":"+ Integer.toString(intent.getIntExtra("data_hour2", 0))+
        	" ~ ");
        time2 = (TextView)findViewById(R.id.Time_content_TO);
        time2.setText(Integer.toString(intent.getIntExtra("data_hour3", 0))+
        	":"+Integer.toString(intent.getIntExtra("data_hour4", 0)));
//		Log.d("id-external", intent.getStringExtra("data_id"));
//		Log.d("mon-external", intent.getStringExtra("data_mon"));
//		Log.d("wed-external", intent.getStringExtra("data_wed"));
        
		Calendar cal = Calendar.getInstance();

		boolean[] week_ = { false, intent.getStringExtra("data_sun").equals("일"),
				intent.getStringExtra("data_mon").equals("월"), 
				intent.getStringExtra("data_tue").equals("화"),
				intent.getStringExtra("data_wed").equals("수"),
				intent.getStringExtra("data_thu").equals("목"),
				intent.getStringExtra("data_fri").equals("금"),
				intent.getStringExtra("data_sat").equals("토") }; // sunday=1 이라서 0의
	try{
//		 if(week_.equals(true)){
		if(intent.getStringExtra("data_mon").equals("월")){
			notnullweek.add("월");}
		if(intent.getStringExtra("data_tue").equals("화")){
			notnullweek.add("화");}
		if(intent.getStringExtra("data_wed").equals("수")){
			notnullweek.add("수");}
		if(intent.getStringExtra("data_thu").equals("목")){
			notnullweek.add("목");}
		if(intent.getStringExtra("data_fri").equals("금")){
			notnullweek.add("금");}
		if(intent.getStringExtra("data_sat").equals("토")){ 
			notnullweek.add("토");}
		if(intent.getStringExtra("data_sun").equals("일")){
			notnullweek.add("일");};
		Log.d("notnull1", notnullweek.toString());

//		 }
//		day.setText(notnullweek.toString());
		
 		
			int len = week_.length;
			
//			if(mSwitch.isChecked()){
		
		int k;
		for (k = 0; k < len; k++) {
			if (week_[k]) {
				Log.v(Integer.toString(k),"STRING");
					day.setText(notnullweek.toString());}

	};
	}catch(Exception e){
		int len = week_.length;

		int k;
		for (k = 0; k < len; k++) {
			if (week_[k]) {
				Log.v(Integer.toString(k),"STRING");
		
		day.setText(notnullweek.toString());
	}
		}

	};
		
     		mSwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
     			//
     						public void onCheckedChanged(CompoundButton cb, boolean isChecking) {
     							if (isChecking) {
     								ContentValues values = new ContentValues();
     								savePreferences("switch_Value", mSwitch.isChecked());
     								String onoff = "ON";
     							    AlarmAdapter.onoff = onoff;
     								values.put(Databases.CreateDB.ONOFF, onoff);
     								
     								Intent intent = getIntent();
     								final int id = Integer.parseInt(intent.getStringExtra("data_id"));
     								
     								DbopenHelper.mDB.update(CreateDB._TABLENAME, values, "_id="+id , null);

     							
     								MainActivity.arrayListAlarmTimeItem.clear();
     								doWhileCursorToArray.doWhileCursorToArray();
     								AlarmAdapter.arrayAdapterAlarmList.setArrayList(MainActivity.arrayListAlarmTimeItem);
     								AlarmAdapter.arrayAdapterAlarmList.notifyDataSetChanged();					

     								MainActivity.mCursor.close();

     								 noti = true;
//     								finish();
     								
     						} else {
     							ContentValues values = new ContentValues();
     							savePreferences("switch_Value", mSwitch.isChecked());

 								String onoff2 = "OFF";
 							    AlarmAdapter.onoff = onoff2;
 								values.put(Databases.CreateDB.ONOFF, onoff2);
 								
 								Intent intent = getIntent();
 								final int id = Integer.parseInt(intent.getStringExtra("data_id"));
 								
 								
 								DbopenHelper.mDB.update(CreateDB._TABLENAME, values, "_id="+id , null);
 							
 								MainActivity.arrayListAlarmTimeItem.clear();
 								doWhileCursorToArray.doWhileCursorToArray();
 								AlarmAdapter.arrayAdapterAlarmList.setArrayList(MainActivity.arrayListAlarmTimeItem);
 								AlarmAdapter.arrayAdapterAlarmList.notifyDataSetChanged();
 								
 								MainActivity.mCursor.close();
					     
//							        finish();
     							noti = false;
     					
     						}

     						}
     		});

	
		
			Log.v("HOUR",Integer.toString(j));
			Log.v("DAY", Integer.toString(cal.get(Calendar.DAY_OF_WEEK)-1));
			
			
//			Intent intent3 = new Intent(this, AlarmReceive.class);   //AlarmReceive.class이클레스는 따로 만들꺼임 알람이 발동될때 동작하는 클레이스임
	        Calendar cal3 = Calendar.getInstance();
	        Calendar cal4 = Calendar.getInstance();
	        int year = cal3.get(Calendar .YEAR);
	        int mon = cal3.get(Calendar .MONTH);
	        int day = cal3.get(Calendar .DAY_OF_MONTH);
	        int hour = jj;
	        int minute = jjjj;
	        int hour2 = jjj;
	        int minute2 = jjjjj;
//	        int sec = cal3.get(Calendar .SECOND);
	        cal3.set(year, mon, day, hour, minute);
	        cal4.set(year, mon, day, hour2, minute2);
	
//	        //알람시간 calendar에 set해주기
		
	    	
	       
//			Intent intent1 = new Intent(modifyScheduleActivity.this, AlarmReceive.class); 
	
			
			
					 
//							Log.v(Integer.toString(oPerlishArray.get(b)), "operlish");
				
				 
							mDbOpenHelper = new DbopenHelper(this);
						
				Log.v("DAY--", Integer.toString(j));

				
					 Log.d("true-noti","true-noti");

				Intent intent1 = new Intent(this, AlarmReceive.class);
			      intent1.putExtra("weekday", week_);
			      intent1.putExtra("calendar", cal3);
			      intent1.putExtra("calendar2", cal4.getTimeInMillis());
			      intent1.putExtra("_time", Integer.toString(j));
			  	AlarmManager am = (AlarmManager)getSystemService (Context.ALARM_SERVICE);
//			  	AlarmManager am2 = (AlarmManager)getSystemService (Context.ALARM_SERVICE);
//			  	AlarmManager am3 = (AlarmManager)getSystemService (Context.ALARM_SERVICE);

			      PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi1 = PendingIntent.getBroadcast(this, 1, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi2 = PendingIntent.getBroadcast(this, 2, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi3 = PendingIntent.getBroadcast(this, 3, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi4 = PendingIntent.getBroadcast(this, 4, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi5 = PendingIntent.getBroadcast(this, 5, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi6 = PendingIntent.getBroadcast(this, 6, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi7 = PendingIntent.getBroadcast(this, 7, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi8 = PendingIntent.getBroadcast(this, 8, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi9 = PendingIntent.getBroadcast(this, 9, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi10 = PendingIntent.getBroadcast(this, 10, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi11 = PendingIntent.getBroadcast(this, 11, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi12 = PendingIntent.getBroadcast(this, 12, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi13 = PendingIntent.getBroadcast(this, 13, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
			      PendingIntent pi14 = PendingIntent.getBroadcast(this, 14, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
//			      if(noti == true){

//					PendingIntent sender = PendingIntent.getBroadcast(
//							modifyScheduleActivity.this, 0, intent1, 0);
					 if(pref.getBoolean("checked", true)){	
						
						 Log.d("true","true");
					int l;
					
					
//				 for(int b = 0; b < q_size-1; b++){
//				
				for (l = 1; l < j; ++l) {
//					while(cal4.getTimeInMillis() == System.currentTimeMillis()){
//						Intent intent1 = new Intent(this, AlarmReceive.class);
					Log.v("after", Integer.toString(l));
					if(l==1 && System.currentTimeMillis() < cal3.getTimeInMillis() + 1*60*1000 + 300000){
					am.setRepeating(AlarmManager.RTC_WAKEUP,
									cal3.getTimeInMillis() + 1*60*1000,
									AlarmManager.INTERVAL_DAY, pi);}
					
					else if(l==2 && System.currentTimeMillis() < cal3.getTimeInMillis() + 2*60*1000 +30000){

			      am.setRepeating(AlarmManager.RTC_WAKEUP,
							cal3.getTimeInMillis() + 2*60*1000,
							AlarmManager.INTERVAL_DAY, pi1);
		
					}
					else if(l==3  && System.currentTimeMillis() < cal3.getTimeInMillis() + 3*60*1000 +30000){
			      am.setRepeating(AlarmManager.RTC_WAKEUP,
							cal3.getTimeInMillis() + 3*60*1000,
							AlarmManager.INTERVAL_DAY, pi2);
			      }
					else if(l==4  && System.currentTimeMillis() < cal3.getTimeInMillis() + 4*60*1000 +30000){

			      am.setRepeating(AlarmManager.RTC_WAKEUP,
							cal3.getTimeInMillis() + 4*60*1000,
							AlarmManager.INTERVAL_DAY, pi3);
					}else if(l==5  && System.currentTimeMillis() < cal3.getTimeInMillis() + 5*60*1000 +30000){

					      am.setRepeating(AlarmManager.RTC_WAKEUP,
									cal3.getTimeInMillis() + 5*60*1000,
									AlarmManager.INTERVAL_DAY, pi4);
					}else if(l==6  && System.currentTimeMillis() < cal3.getTimeInMillis() + 6*60*1000 +30000){

						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 6*60*1000,
								AlarmManager.INTERVAL_DAY, pi5);
					}else if(l==7  && System.currentTimeMillis() < cal3.getTimeInMillis() + 7*60*1000 +30000){
						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 7*60*1000,
								AlarmManager.INTERVAL_DAY, pi6);
					}else if(l==8  && System.currentTimeMillis() < cal3.getTimeInMillis() + 8*60*1000 +30000){

						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 8*60*1000,
								AlarmManager.INTERVAL_DAY, pi7);
					}else if(l==9  && System.currentTimeMillis() < cal3.getTimeInMillis() + 9*60*1000 +30000){

						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 9*60*1000,
								AlarmManager.INTERVAL_DAY, pi8);
					}else if(l==10  && System.currentTimeMillis() < cal3.getTimeInMillis() + 10*60*1000 +30000){

						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 10*60*1000,
								AlarmManager.INTERVAL_DAY, pi9);
					}else if(l==11  && System.currentTimeMillis() < cal3.getTimeInMillis() + 11*60*1000 +30000){

						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 11*60*1000,
								AlarmManager.INTERVAL_DAY, pi10);
					}else if(l==12  && System.currentTimeMillis() < cal3.getTimeInMillis() + 12*60*1000 +30000){

						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 12*60*1000,
								AlarmManager.INTERVAL_DAY, pi11);
					}else if(l==13  && System.currentTimeMillis() < cal3.getTimeInMillis() + 13*60*1000 +30000){

						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 13*60*1000,
								AlarmManager.INTERVAL_DAY, pi12);
					}else if(l==14  && System.currentTimeMillis() < cal3.getTimeInMillis() + 14*60*1000 +30000){

						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 14*60*1000,
								AlarmManager.INTERVAL_DAY, pi13);
					}else if(l==15  && System.currentTimeMillis() < cal3.getTimeInMillis() + 15*60*1000 +30000){

						  am.setRepeating(AlarmManager.RTC_WAKEUP,
								cal3.getTimeInMillis() + 15*60*1000,
								AlarmManager.INTERVAL_DAY, pi14);

						  
					}
						}
				}
				}
//					}
//					if(l==j-1){
//						Log.d("cancel","cancel");
//						 am.cancel(pi);}
//				}
//					am.set(AlarmManager.RTC_WAKEUP, cal3.getTimeInMillis() + l*60*1000, pi);
//			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
//							gregorianCalendar.getTimeInMillis() + l
//									* 60 * 1000,
//							AlarmManager.INTERVAL_DAY, sender);
		
//			if(l == j-1){
//			Log.d("cancel","cancel");
////		    PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
//		    am.cancel(pi);
//			}
//			}	
	
	//mswitch에서 boolean값 받아서 alarm
	  private void savePreferences(String key, boolean value) {
		          SharedPreferences sharedPreferences = PreferenceManager
		                  .getDefaultSharedPreferences(this);
		          Editor editor = sharedPreferences.edit();
		          editor.putBoolean(key, value);
		          editor.commit();
		      }
//
	  private void loadSavedPreferences() {
		          SharedPreferences sharedPreferences = PreferenceManager

		                  .getDefaultSharedPreferences(this);

		          boolean switchValue = sharedPreferences.getBoolean("switch_Value", false);

		          if (switchValue) {
		        	 
		        	  Intent intent = getIntent();
		          if(AlarmAdapter.onoff =="OFF"){
//		        	  MainActivity.switch_on_off.setChecked(false);
		        	  mSwitch.setChecked(false);
		          } else if(AlarmAdapter.onoff =="ON"){
		        	  mSwitch.setChecked(true);
		          }
		      }
	  }
//					  continue;
				
	        
				 
//				 }
	
//}
	public void onClickView(View v){
        int id = v.getId();
		if (id == R.id.fix_time) {
			Log.d("plz","plz");
			mCustomDialog = new CustomDialog(this, 
                    leftClickListener, 
                    rightClickListener,
                    thirdClickListener);
			mCustomDialog.show();
		}
		if (id == R.id.confirm){
			MainActivity.arrayListAlarmTimeItem.clear();
			doWhileCursorToArray.doWhileCursorToArray();
			AlarmAdapter.arrayAdapterAlarmList.setArrayList(MainActivity.arrayListAlarmTimeItem);
			AlarmAdapter.arrayAdapterAlarmList.notifyDataSetChanged();
			MainActivity.mCursor.close();
			 try { Thread.sleep(500);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
			Toast.makeText(getApplicationContext(), "Alarm Confirmed!",
					Toast.LENGTH_SHORT).show();
//			this.finish();
        	Intent intent11 = new Intent(this, tabMainActivity.class);
        	startActivity(intent11);
        	finish();

		}
    }
	 private View.OnClickListener thirdClickListener = new View.OnClickListener() {
		 @Override
	        public void onClick(View v) {
			
				mMainDialog = createDialog();
				mMainDialog.show();
			
			};
		 private AlertDialog createDialog() {
				final View innerView = getLayoutInflater().inflate(R.layout.dialog_layout, null);
				AlertDialog.Builder ab = new AlertDialog.Builder(modifyScheduleActivity.this);
				ab.setTitle("Day Of Week");
				ab.setView(innerView);
		
				
				mon_check = (CheckBox)innerView.findViewById(R.id.cb_01);
				tue_check =	(CheckBox)innerView.findViewById(R.id.cb_02);
				wed_check =	(CheckBox)innerView.findViewById(R.id.cb_03);
				thu_check =	(CheckBox)innerView.findViewById(R.id.cb_04);
				fri_check =	(CheckBox)innerView.findViewById(R.id.cb_05);
				sat_check =	(CheckBox)innerView.findViewById(R.id.cb_06);
				sun_check =	(CheckBox)innerView.findViewById(R.id.cb_07); 

					
				Intent intent = getIntent();
				final int id = Integer.parseInt(intent.getStringExtra("data_id"));
//					Log.d("월",intent.getStringExtra("data_mon"));		
				try{
					  if(intent.getStringExtra("data_mon").equals("월")){
				        	mon_check.setChecked(true);
				        } if(intent.getStringExtra("data_tue").equals("화")){
				        	tue_check.setChecked(true);}
				        	if(intent.getStringExtra("data_wed").equals("수")){
				        	wed_check.setChecked(true);
				        }    if(intent.getStringExtra("data_thu").equals("목")){
				        	thu_check.setChecked(true);	
				        }  if(intent.getStringExtra("data_fri").equals("금")){
				        	fri_check.setChecked(true);
				        }  if(intent.getStringExtra("data_sat").equals("토")){
				        	sat_check.setChecked(true);
				        }  if(intent.getStringExtra("data_sun").equals("일")){
				        	sun_check.setChecked(true);
				        }	
				}catch (Exception ex){
					 if(intent.getStringExtra("data_mon")=="월"){
				        	mon_check.setChecked(true);
				        } if(intent.getStringExtra("data_tue")=="화"){
				        	tue_check.setChecked(true);}
				        	if(intent.getStringExtra("data_wed")=="수"){
				        	wed_check.setChecked(true);
				        }    if(intent.getStringExtra("data_thu")=="목"){
				        	thu_check.setChecked(true);	
				        }  if(intent.getStringExtra("data_fri")=="금"){
				        	fri_check.setChecked(true);
				        }  if(intent.getStringExtra("data_sat")=="토"){
				        	sat_check.setChecked(true);
				        }  if(intent.getStringExtra("data_sun")=="일"){
				        	sun_check.setChecked(true);
				        }	
				      
				}
				 
						
				ab.setPositiveButton("설정", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
					        String mon = null;
							String tue = null;
							String wed = null;
							String thu = null;
							String fri = null;
							String sat = null;
							String sun = null;

						ContentValues values = new ContentValues();
//						Intent intent = getIntent();
//				        final int id = Integer.parseInt(intent.getStringExtra("data_id")); //전달된 값을 받음
//						
						if(notnullweek.contains("월")){
							notnullweek.remove("월"); 
						};
						if(mon_check.isChecked() == true){
							notnullweek.add("월");
						mon = "월";
					    AlarmAdapter.mMon = mon;
						}else if(mon_check.isChecked() == false){
							mon = "";
						    AlarmAdapter.mMon = mon;
						}
					
							
						if(notnullweek.contains("화")){
							notnullweek.remove("화"); 
						};
						if(tue_check.isChecked() == true){
							notnullweek.add("화");
						tue = "화";
						AlarmAdapter.mTue = tue;
						}else if(tue_check.isChecked() == false){
							tue = "";
						    AlarmAdapter.mTue = tue;
						};
						
						if(notnullweek.contains("수")){
							notnullweek.remove("수"); 
						};
						if(wed_check.isChecked() == true){
							notnullweek.add("수");
						wed = "수";
						AlarmAdapter.mWed = wed;
						}else if(wed_check.isChecked() == false){
							wed = "";
						    AlarmAdapter.mWed = wed;
						};

						
						if(notnullweek.contains("목")){
							notnullweek.remove("목"); 
						};
						if(thu_check.isChecked() == true){						
						notnullweek.add("목");
						thu = "목";
						AlarmAdapter.mThu = thu;
						}else if(thu_check.isChecked() == false){
							thu = "";
						    AlarmAdapter.mThu = thu;
						};
						
						if(notnullweek.contains("금")){
							notnullweek.remove("금");
						};
						if(fri_check.isChecked() == true){
							notnullweek.add("금");
						fri = "금";
						AlarmAdapter.mFri = fri;
						}else if(fri_check.isChecked() == false){
							fri = "";
						    AlarmAdapter.mFri = fri;
						};
						
						if(notnullweek.contains("토")){
							notnullweek.remove("토"); 
						};
						if(sat_check.isChecked() == true){
						notnullweek.add("토");
						sat = "토";
						AlarmAdapter.mSat = sat;
						}else if(sat_check.isChecked() == false){
							sat = "";
						    AlarmAdapter.mSat = sat;
						};
						
						if(notnullweek.contains("일")){
							notnullweek.remove("일"); 
						};
						if(sun_check.isChecked() == true){
						notnullweek.add("일");
						sun = "일";
						AlarmAdapter.mSun = sun;
						}else if(sun_check.isChecked() == false){
							sun = "";
						    AlarmAdapter.mSun = sun;
						};
						
						values.put(Databases.CreateDB.MON, mon);
						values.put(Databases.CreateDB.TUE, tue);
						values.put(Databases.CreateDB.WED, wed);
						values.put(Databases.CreateDB.THU, thu);
						values.put(Databases.CreateDB.FRI, fri);
						values.put(Databases.CreateDB.SAT, sat);
						values.put(Databases.CreateDB.SUN, sun);

						DbopenHelper.mDB.update(CreateDB._TABLENAME, values, "_id="+id , null);
//						Log.d("id", intent.getStringExtra("data_id"));
//						Log.d("modify", tue);
					
						MainActivity.arrayListAlarmTimeItem.clear();
						doWhileCursorToArray.doWhileCursorToArray();
						AlarmAdapter.arrayAdapterAlarmList.setArrayList(MainActivity.arrayListAlarmTimeItem);
						AlarmAdapter.arrayAdapterAlarmList.notifyDataSetChanged();
						

						MainActivity.mCursor.close();
					
			           	  day.setText(notnullweek.toString());
			           	  Log.d("not", notnullweek.toString());
//						  day.setText(notnullweek.toString());
					

						 try { Thread.sleep(500);
			                } catch (InterruptedException e) {
			                    e.printStackTrace();
			                }
						
						setDismiss(mMainDialog);
						setDismiss(mCustomDialog);
					
					}
				});
				
				ab.setNegativeButton("취소", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						setDismiss(mMainDialog);
						setDismiss(mCustomDialog);
					}
				});
					
				return  ab.create();
			}
		 
			private void setDismiss(Dialog dialog){
				if(dialog!=null&&dialog.isShowing())
					dialog.dismiss();
			}
			 
		 	};
		
	 private View.OnClickListener leftClickListener = new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	// TODO Auto-generated method stub
				new TimePickerDialog(modifyScheduleActivity.this, t, datetime
						.get(Calendar.HOUR_OF_DAY), datetime
						.get(Calendar.MINUTE), true).show();
				AlarmAdapter.mHour = datetime.get(Calendar.HOUR_OF_DAY);
				AlarmAdapter.mMinute = datetime.get(Calendar.MINUTE);
				mCustomDialog.dismiss();
			}
		
			TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay1, int minute1) {
						// TODO Auto-generated method stub
						MainActivity.gregorianCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay1);
						MainActivity.gregorianCalendar.set(Calendar.MINUTE, minute1);
						AlarmAdapter.mHour = hourOfDay1;
						AlarmAdapter.mMinute = minute1;
						
//						RealMainActivity.mDbOpenHelper.updateColumn(id0, a1, a2, a3, a4, a5, a6, a7, hourOfDay, minute, hour3, hour4);
//						DbopenHelper.mDB.execSQL("UPDATE stretching_alarm SET update FROMTIMEHOUR = '업데이트 할 문자열' WHERE 조건이 되는 컬럼 = '값';");
//						doWhileCursorToArray();

						ContentValues values = new ContentValues();
						
						Intent intent = getIntent();
				        final int id = Integer.parseInt(intent.getStringExtra("data_id")); //전달된 값을 받음

						values.put(Databases.CreateDB.FROMTIMEHOUR, hourOfDay1);
						values.put(Databases.CreateDB.FROMTIMEMINUTE, minute1);
						

						DbopenHelper.mDB.update(CreateDB._TABLENAME, values, "_id="+id , null);

						Log.d("id", intent.getStringExtra("data_id"));
						Log.d("modify", Integer.toString(hourOfDay1));


						MainActivity.arrayListAlarmTimeItem.clear();


						doWhileCursorToArray.doWhileCursorToArray();
				
						AlarmAdapter.arrayAdapterAlarmList.setArrayList(MainActivity.arrayListAlarmTimeItem);
						AlarmAdapter.arrayAdapterAlarmList.notifyDataSetChanged();
		

						MainActivity.mCursor.close();
					
						time.setText(Integer.toString(hourOfDay1)+ ":"
								+Integer.toString(minute1) + " ~ " );
						 try { Thread.sleep(500);
			                } catch (InterruptedException e) {
			                    e.printStackTrace();
			                }
					}
			};

    };

	 
	    private View.OnClickListener rightClickListener = new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	new TimePickerDialog(modifyScheduleActivity.this, t2, datetime2
						.get(Calendar.HOUR_OF_DAY), datetime2
						.get(Calendar.MINUTE), true).show();
	        	AlarmAdapter.mHour2 = datetime2.get(Calendar.HOUR_OF_DAY);
	        	AlarmAdapter.mMinute2 = datetime2.get(Calendar.MINUTE);
				mCustomDialog.dismiss();

			}
		
			TimePickerDialog.OnTimeSetListener t2 = new TimePickerDialog.OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay2, int minute2) {
						// TODO Auto-generated method stub
						MainActivity.gregorianCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay2);
						MainActivity.gregorianCalendar.set(Calendar.MINUTE, minute2);
						AlarmAdapter.mHour2 = hourOfDay2;
						AlarmAdapter.mMinute2 = minute2;
						
						ContentValues values = new ContentValues();
						
						Intent intent = getIntent();

						values.put(Databases.CreateDB.TOTIMEHOUR,  hourOfDay2);
						values.put(Databases.CreateDB.TOTIMEMINUTE, minute2);
//						mDbOpenHelper.updateColumn(id,a,b,c, d,e,f,g, 
//								hourOfDay, minute, q3, q4);
						DbopenHelper.mDB.update(CreateDB._TABLENAME, values, "_id="+intent.getStringExtra("data_id") , null);
//						DbopenHelper.mDB.update(CreateDB._TABLENAME, values, "TOTIMEHOUR="+hourOfDay2, null);
//						DbopenHelper.mDB.update(CreateDB._TABLENAME, values, "TOTIMEMINUTE="+minute2, null);
						Log.d("modify", Integer.toString(hourOfDay2));

						Log.d("id", intent.getStringExtra("data_id"));

						AlarmAdapter.arrayAdapterAlarmList.setArrayList(MainActivity.arrayListAlarmTimeItem);
						AlarmAdapter.arrayAdapterAlarmList.notifyDataSetChanged();
//						MainActivity.arrayListAlarmTimeItem = new ArrayList<AlarmData>();
//
						MainActivity.arrayListAlarmTimeItem.clear();
//
						doWhileCursorToArray.doWhileCursorToArray();
//						
		

						MainActivity.mCursor.close();
						time2.setText(Integer.toString(hourOfDay2)+ ":"
								+Integer.toString(minute2));
						
						 try { Thread.sleep(500);
			                } catch (InterruptedException e) {
			                    e.printStackTrace();
			                }
					}
			
			};
		
	    };
	    
	  
	    public void setArrayList(ArrayList<AlarmData> arrays){
			AlarmAdapter.arrayListAlarmDatas = arrays;

		}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
}

			
